<?php
/**
 * Created by PhpStorm.
 * User: xuke
 * Date: 16/5/20
 * Time: 下午2:30
 */
namespace App\Logic;
use App\Http\Model\Users as UsersModel;
use Illuminate\Support\Facades\Redis;

class UserLogic extends BaseLogic
{
    protected $_user;
    protected $_iscache;

    public function __construct(UsersModel $model, $iscache = 0)
    {
        $this->_user = $model;
        $this->_iscache = $iscache;
    }

    public static function initByUser($user, $iscache = 0)
    {
        if (is_numeric($user)) {
            if (!$iscache) //如果使用缓存
            {
                $model = UsersModel::find($user);
            }else{
                $userkey = 'user_'.$user;
                if (Redis::exists($userkey))
                {
                    $model = unserialize(Redis::get($userkey));
                }else{
                    $model = UsersModel::find($user);
                    Redis::set($userkey, serialize($model));
                }
            }
            
        }
        if ($user instanceof UsersModel)
        {
            $model = $user;
        }
        return new static($model, $iscache);
    }

    public static function create($iscache = 0)
    {
        $model = new UsersModel();
        return new static($model, $iscache);
    }

    public function save($data)
    {
        if($bool = $this->_user->fill($data)->save() && $this->_iscache)
        {
            $userkey = 'user_'.$this->_user['user_id'];
            Redis::set($userkey, serialize($this->_user));
        }
        return $bool;
    }

    /**
     * 移动端接口数据返回规范
     */
    public function toApi()
    {
        
    }
}